﻿@inherits BaseComponent
@typeparam TItem where TItem : class, new()

<div class="boot-query">
@if (Model.QueryColumns != null && Model.QueryColumns.Count > 0)
{
    var length = Model.QueryColumns.Count;
    if (length > 3)
        length = _expand ? length : 3;
    @for (var i = 0; i < length; i++)
    {
        var item = Model.QueryColumns[i];
        var itemName = Language.GetString<TItem>(item);
        var itemType = "String";
        if (item.Property != null)
            itemType = item.Property.PropertyType.Name;
        <div class="item">
            <label>@itemName</label>
            @if (!string.IsNullOrWhiteSpace(item.Category))
            {
                var codes = Cache.GetCodes(item.Category).ToCodes(item.IsQueryAll ? Language["All"] : "");
                <BootstrapInput @bind-Value="@(Model.QueryData[item.Id].Value)" style="width:180px" />
                @* <BootSelect Codes="codes" @bind-Value="@(Model.QueryData[item.Id].Value)" style="width:180px" /> *@
            }
            else if (itemType.Contains("DateTime"))
            {
                <DateTimeRange OnConfirm="e=>OnDateRangeConfirm(e, Model.QueryData[item.Id])" />
            }
            else
            {
                <BootstrapInput @bind-Value="@(Model.QueryData[item.Id].Value)" style="width:180px" />
            }
        </div>
    }
    <div style="margin-left:10px;">
            <Button Color="Color.Primary" OnClick="e=>OnSearchAsync()">@Language.Search</Button>
            <Button Color="Color.Primary" OnClick="e=>ShowAdvSearch()">@Language.AdvSearch</Button>
            @* <Button style="margin-left:8px;" OnClick="()=>{_form?.Reset();}">@Language.Reset</Button> *@
        @if (length > 3)
        {
            @* <a style="margin-left:8px;font-size:12px;" @onclick="()=>{_expand=!_expand;}">
    <Icon Type="@(_expand ? "up" : "down")"></Icon> @(_expand ? Language["Collapse"] : Language["Expand"])
    </a> *@
        }
    </div>
}
</div>

@code {
    bool _expand = false;

    [Parameter] public TableModel<TItem> Model { get; set; }

    private async Task OnSearchAsync()
    {
        Model.Criteria.IsQuery = true;
        Model.Criteria.Query = Model.QueryData.Select(d => d.Value).ToList();
        await Model.RefreshAsync();
    }

    private Task OnDateRangeConfirm(DateTimeRangeValue value, QueryInfo query)
    {
        query.Value = $"{value.Start:yyyy-MM-dd}~{value.End:yyyy-MM-dd}";
        return Task.CompletedTask;
    }

    private void ShowAdvSearch() => Model.ShowAdvancedSearch();
}